import React, { useState, useEffect, useMemo, useCallback, use } from "react"
import styles from "./index.module.less"
import { Button, Space, Table, type TableProps } from "antd"
import type { TablePlusProps, ColumnPlusType } from "./types"
import { isUniqueKey, formatNumberWithCommas } from "../../utiles"
import ToolBar from "./ToolBar"
import { TableProvider } from "./context"

const OperationColumn = React.memo(({
  record,
  index,
  operateColumn,
  rowActions
}: {
  record: any;
  index: number;
  operateColumn: ColumnPlusType;
  rowActions: any[];
}) => {
  // 获取原始的自定义render结果(如果存在)
  const customRender = operateColumn.render ? operateColumn.render(undefined, record, index) : null;

  // 合并操作按钮逻辑
  const columnOperations = operateColumn.operations || [];
  const hasRowActions = Array.isArray(rowActions) && rowActions.length > 0;
  const hasColumnOperations = columnOperations.length > 0;

  // 合并操作按钮
  const mergedOperations = hasRowActions
    ? [...columnOperations, ...rowActions]
    : columnOperations;

  if (!hasColumnOperations && !hasRowActions && !customRender) {
    return null;
  }

  // 校验操作按钮key的唯一性
  if (mergedOperations.length > 0 && !isUniqueKey(mergedOperations)) {
    console.error(`操作按钮中存在重复的key值，这可能导致出现问题，请检查并确保每个操作按钮的key是唯一的`);
  }

  const operationsRender = (hasColumnOperations || hasRowActions) ? (
    <Space size={2}>
      {mergedOperations.map((op) => {
        const isShow = typeof op.show === 'function' ? op.show(record, index) : op.show == undefined ? true : op.show;
        return (
          isShow && (
            <Button
              key={op.key}
              type="link"
              onClick={() => operateColumn.operateClick?.(op.key, record)}
              {...op.buttonProps}
              style={{ padding: '6px', ...op.buttonProps?.style }}
            >
              {op.label}
            </Button>
          )
        )
      })}
    </Space>
  ) : null;

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      {customRender && <>{customRender}</>}
      {operationsRender}
    </div>
  );
});

export const TablePlus: React.FC<TablePlusProps> = (props) => {
  const { columns, dataSource, request, toolBarRender, options, pagination, params } = props
  const [tableData, setTableData] = useState<any[]>(dataSource || [])
  const [loading, setLoading] = useState<boolean>(props.loading || false)
  const [currentPage, setCurrentPage] = useState<number>(pagination ? pagination?.current || 1 : 1)
  const [pageSize, setPageSize] = useState<number>(pagination ? pagination?.pageSize || 10 : 0)
  const [total, setTotal] = useState<number>(pagination ? pagination?.total || 0 : 0)
  const [selectRows, setSelectRows] = useState<any[]>([]);
  const [localColumns, setLocalColumns] = useState<ColumnPlusType[]>(columns);

  const originColumns = useMemo(() => {
    const operateColumn = localColumns.find(item => item.dataIndex === 'operation');
    if (!operateColumn) return localColumns;
    // 创建一个新的列对象，覆盖 render 方法
    const newOprateColumn: ColumnPlusType = {
      ...operateColumn,
      render: (_: any, record: any, index: number) => {
        const rowActions = tableData[index]?.actions || [];
        return (
          <OperationColumn
            record={record}
            index={index}
            operateColumn={operateColumn}
            rowActions={rowActions}
          />
        );
      },
    };

    return localColumns.map(col => col.dataIndex === 'operation' ? newOprateColumn : col);
  }, [localColumns, tableData]);

  const fetchData = async () => {
    if (!dataSource && request) {
      setLoading(true)
      try {
        const res = await request({ page: currentPage, pageSize, ...params });
        setTableData(res.data || [])
        setTotal(res.total || 0)
      } catch (error) {
        console.error('获取数据出错:', error)
      } finally {
        setLoading(false)
      }
    }
  }

  useEffect(() => {
    fetchData();
  }, [request, dataSource, currentPage, pageSize])

  useEffect(() => {
    if (params && currentPage !== 1) {
      setCurrentPage(1);
    }
    if (currentPage === 1 && params) {
      fetchData();
    }
  }, [params])



  const rowSelection = useMemo<TableProps['rowSelection']>(() => ({
    onChange: (_, selectedRows: any[]) => {
      setSelectRows(selectedRows);
    },
  }), []);

  const paginationConfig = useMemo(() => {
    if (pagination === false) return false;

    return {
      current: currentPage,
      pageSize: pageSize,
      total: total,
      showSizeChanger: true,
      showQuickJumper: true,
      onChange: (page: number, size: number) => {
        setCurrentPage(page);
        setPageSize(size);
        if (pagination && pagination.onChange) {
          pagination.onChange(page, size);
        }
      }
    };
  }, [currentPage, pageSize, total, pagination]);

  const contextValue = useMemo(() => ({
    selectRows,
    columns: localColumns,
    setColumns: setLocalColumns
  }), [selectRows, localColumns]);

  return (
    <TableProvider contextValue={contextValue}>
      <div className={styles.wrapper}>
        <div className={styles.tableHeader}>
          <div className={styles.title}>
            {props.tableHeaderTitle || `全部数据 ${formatNumberWithCommas(total, 0)}`}
          </div>
          <div className={styles.toolBar}>
            <Space>
              {toolBarRender && toolBarRender()}
              <ToolBar options={options || {}} />
            </Space>
          </div>
        </div>

        <Table
          rowKey="id"
          rowSelection={{
            type: 'checkbox',
            ...rowSelection
          }}
          {...props}
          loading={loading}
          dataSource={tableData}
          columns={originColumns.filter(col => col.hidden !== true)}
          pagination={paginationConfig}
        />
      </div>
    </TableProvider>
  );
};

export default TablePlus;